package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/author")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        System.out.println(blogId);
        if(blogId == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("参数非法，缺少 blogId ！");
            return;
        }
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectById(Integer.parseInt(blogId));

        if(blog == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未找到指定的博客，blogId = " + blogId);
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        HttpSession session = req.getSession(false);
        User author = (User) session.getAttribute("user");
        author.setSame(author.getUserId() == blog.getUserId() ? 1 : 0);
        user.setSame(author.getUserId() == blog.getUserId() ? 1 : 0);
        System.out.println(user.getSame());
        String respJson = objectMapper.writeValueAsString(user);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respJson);

    }
}
